import 'package:carousel_slider/carousel_slider.dart';
import 'package:dmz/base/pageWidget/base_stateful_widget.dart';
import 'package:dmz/base/widget/defult_widget.dart';
import 'package:dmz/business/find/controller/find_main_controller.dart';
import 'package:dmz/business/find/model/find_model.dart';
import 'package:dmz/utils/sp_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

class FindMainWidgets {
  static Widget titeWidget(
      int selectIndex, Function(int tag, {bool? reload}) onRefresh) {
    List<String> titles = ['全部'.tr, '用车技巧'.tr, '智能知识'.tr];
    titleItem(int tag, int index) {
      var select = tag == index;
      return Expanded(
          child: Container(
              color: Colors.transparent,
              height: 120.sp,
              child: Column(children: [
                Expanded(
                    child: Center(
                        child: DefaultText(titles[tag], select ? 40.sp : 28.sp,
                            textColor: select
                                ? const Color(0xFF23C565)
                                : const Color(0xFF919191),
                            fontWeight:
                                select ? FontWeight.w700 : FontWeight.normal))),
                Container(
                    height: 5.sp,
                    color:
                        select ? const Color(0xFF23C565) : Colors.transparent)
              ])).addGestureDetector(() {
        onRefresh(tag);
        // pageController.jumpToPage(tag);
      }));
    }

    return Row(children: [
      titleItem(0, selectIndex),
      titleItem(1, selectIndex),
      titleItem(2, selectIndex),
    ]);
  }

  static contentWidget(
      pageController,
      allDatas,
      Future<void> Function(int tag, {bool? reload}) onRefresh,
      Future<void> Function(int tag, int index) loadMore) {
    return Expanded(
        child: PageView.builder(
            itemCount: 3,
            controller: pageController,
            itemBuilder: ((context, index) {
              return FindListPageWidget(
                  tag: index, onRefresh: onRefresh, loadMore: loadMore);
            })));
  }
}

class CarouselSliderWidget extends StatefulWidget {
  final List<String> imageUrls;
  const CarouselSliderWidget({super.key, required this.imageUrls});

  @override
  State<CarouselSliderWidget> createState() => _CarouselSliderWidgetState();
}

class _CarouselSliderWidgetState extends State<CarouselSliderWidget> {
  int _current = 0;
  @override
  Widget build(BuildContext context) {
    return Container(
        padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
        color: Colors.transparent,
        child: Stack(alignment: Alignment.bottomCenter, children: <Widget>[
          CarouselSlider(
              options: CarouselOptions(
                  height: 400.sp,
                  // aspectRatio: 16 / 9,
                  viewportFraction: 1.5,
                  initialPage: 0,
                  enableInfiniteScroll: true,
                  reverse: false,
                  autoPlay: true,
                  autoPlayInterval: const Duration(seconds: 5),
                  autoPlayAnimationDuration: const Duration(milliseconds: 800),
                  autoPlayCurve: Curves.fastOutSlowIn,
                  enlargeCenterPage: true,
                  onPageChanged: (index, reason) {
                    setState(() {
                      _current = index;
                    });
                  },
                  scrollDirection: Axis.horizontal),
              items: widget.imageUrls.map((imagePath) {
                return Builder(builder: (BuildContext context) {
                  return Container(
                      color: Colors.transparent,
                      child: DefaultNetWorkImage(
                        imagePath,
                        width: 760.sp,
                        height: 400.sp,
                      )).didClipRRectAll(16.sp);
                });
              }).toList()),
          Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: widget.imageUrls.map((url) {
                int index = widget.imageUrls.indexOf(url);
                return Container(
                    width: 12.sp,
                    height: 12.sp,
                    margin: EdgeInsets.symmetric(
                        vertical: 16.sp, horizontal: 16.sp),
                    decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: _current == index
                            ? const Color(0xFF23C565)
                            : const Color(0xFFF9F9F9)));
              }).toList())
        ]));
  }
}

class FindListPageWidget extends StatefulWidget {
  final int tag;
  // final List<FindListData> datas;
  final Future<void> Function(int tag) onRefresh;
  final Future<void> Function(int tag, int index) loadMore;
  const FindListPageWidget(
      {super.key,
      required this.tag,
      required this.onRefresh,
      required this.loadMore});

  @override
  State<FindListPageWidget> createState() => _FindListPageWidgetState();
}

class _FindListPageWidgetState extends State<FindListPageWidget>
    with AutomaticKeepAliveClientMixin {
  final ScrollController _scrollController = ScrollController();
  bool _isLoadingMore = false;
  int index = 1;

  @override
  bool get wantKeepAlive => true;

  Future<void> _loadMore() async {
    var datas = Get.find<FindPageController>().allDatas[widget.tag];
    if (_isLoadingMore) return;
    if (datas.length % 10 > 0) return;
    _isLoadingMore = true;
    index++;
    await widget.loadMore(widget.tag, index);
    _isLoadingMore = false;
  }

  @override
  void initState() {
    super.initState();

    _scrollController.addListener(_scrollListener);
  }

  void _scrollListener() {
    if (_scrollController.position.extentAfter < 500) {
      _loadMore();
    }
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return GetBuilder<FindPageController>(
        id: 'find${widget.tag}',
        builder: (controller) {
          debugPrint('页面刷新 ---  ');
          return RefreshIndicator(
              color: const Color(0xFF999999),
              onRefresh: () => widget.onRefresh(widget.tag),
              child: ListView.builder(
                  controller: _scrollController,
                  itemCount: controller.allDatas[widget.tag].length + 1,
                  itemBuilder: (context, index) {
                    if (index == controller.allDatas[widget.tag].length) {
                      return _isLoadingMore
                          ? const Padding(
                              padding: EdgeInsets.all(8.0),
                              child: Center(
                                  child: CircularProgressIndicator(
                                color: Color(0xFF999999),
                              )),
                            )
                          : const SizedBox.shrink();
                    }
                    return item(controller.allDatas[widget.tag][index]);
                  }));
        });
  }

  item(FindListData data) {
    return Container(
        padding: EdgeInsets.only(
            top: 36.sp, bottom: 36.sp, left: 30.sp, right: 30.sp),
        color: const Color(0xFF434650),
        child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(children: [
                DefaultNetWorkImage(data.head_img ?? '',
                        width: 112.sp, height: 112.sp)
                    .didClipRRectAll(112.sp),
                Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                  DefaultText(data.nick_name ?? '', 36.sp,
                      textColor: const Color(0xFFF9F9F9),
                      fontWeight: FontWeight.w700),
                  DefaultText(
                      SPUtils.timeIntToTimeStr(data.created_at ?? 0), 28.sp,
                      textColor: const Color(0xFF999999),
                      fontWeight: FontWeight.w700)
                ]).marginOnly(left: 34.sp)
              ]),
              DefaultText(data.title, 40.sp,
                      textColor: const Color(0xFFF9F9F9),
                      fontWeight: FontWeight.w700)
                  .marginOnly(top: 20.sp, bottom: 10.sp),
              DefaultNetWorkImage(data.url ?? '', height: 450.sp)
                  .didClipRRectAll(16.sp)
            ])).didClipRRectAll(16.sp).marginOnly(bottom: 20.sp);
  }
}
